package org.liuyuantao.thread.concurrent;

import java.util.Random;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 获取线程返回值
 */
public class CallableAndFuture {

    /**
     * @param args
     */
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        //提交一个任务获取返回值
        Future<String> future =
                threadPool.submit(
                        //Callable接口只有一个方法,可以使用lambda表达式
                        () -> {
                            Thread.sleep(2000);
                            return "hello";
                        }
                );
        System.out.println("等待结果!");
        try {
            System.out.println("拿到结果：" + future.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("******************************************");
        ExecutorService threadPool2 = Executors.newFixedThreadPool(10);
        //提交一组任务来获取返回值,哪个任务完成了就获取哪个,有点类似偷菜,哪颗菜种好了就收哪颗
        CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2);
        for (int i = 1; i <= 10; i++) {
            final int seq = i;
            completionService.submit(() -> {
                Thread.sleep(new Random().nextInt(5000));
                return seq;
            });
        }
        for (int i = 0; i < 10; i++) {
            try {
                System.out.println(
                        completionService.take().get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }


}
